<template>
  <el-dialog v-model="visible" :title="`${paramsProps.title}`" :destroy-on-close="true" width="580px" draggable>
    <el-form
      ref="ruleFormRef"
      label-width="140px"
      label-suffix=" :"
      :rules="rules"
      :model="paramsProps.row"
      @submit.enter.prevent="handleSubmit"
    >
      <el-form-item label="车辆编号" prop="vehicleNumber">
        <el-input v-model="paramsProps.row.vehicleNumber" placeholder="请填写车辆编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="title">
        <el-input v-model="paramsProps.row.title" placeholder="请填写名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="排班时间" prop="scheduleId">
        <el-tree-select
          v-model="paramsProps.row.scheduleId"
          :data="scheduleList"
          check-strictly
          placeholder="请选择时间"
          :render-after-expand="false"
          clearable
          :default-expand-all="true"
          :props="scheduleProps"
          @change="handleScheduleChange"
        />
      </el-form-item>
      <!-- 动态司机姓名字段和手机号字段 -->
      <div v-if="selectedScheduleType">
        <!-- 第一个司机使用 driverName 和 driverPhone1 -->
        <el-form-item label="司机1姓名" prop="driverName">
          <el-input v-model="paramsProps.row.driverName" placeholder="请填写司机1姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="司机1手机号" prop="driverPhone1">
          <el-input v-model="paramsProps.row.driverPhone1" placeholder="请填写司机1手机号" clearable></el-input>
        </el-form-item>
        <!-- 第二个及以后司机使用 driverName2, driverName3 等和对应的手机号 -->
        <template v-for="index in getDriverCountByScheduleType(selectedScheduleType) - 1" :key="index + 1">
          <el-form-item :label="`司机${index + 1}姓名`" :prop="`driverName${index + 1}`">
            <el-input v-model="paramsProps.row[`driverName${index + 1}`]" :placeholder="`请填写司机${index + 1}姓名`" clearable></el-input>
          </el-form-item>
          <el-form-item :label="`司机${index + 1}手机号`" :prop="`driverPhone${index + 1}`">
            <el-input v-model="paramsProps.row[`driverPhone${index + 1}`]" :placeholder="`请填写司机${index + 1}手机号`" clearable></el-input>
          </el-form-item>
        </template>
      </div>
      <div v-else>
        <el-form-item label="司机姓名" prop="driverName">
          <el-input v-model="paramsProps.row.driverName" placeholder="请填写司机姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="司机手机号" prop="driverPhone1">
          <el-input v-model="paramsProps.row.driverPhone1" placeholder="请填写司机手机号" clearable></el-input>
        </el-form-item>
      </div>

      <!-- <el-form-item label="排序" prop="sort">
        <el-input-number v-model="paramsProps.row.sort" :precision="0" :min="1" :max="999999" />
      </el-form-item> -->
      <el-form-item label="车辆类型" prop="vehicleTypeCd">
        <el-select v-model="paramsProps.row.vehicleTypeCd" clearable placeholder="请选择车辆类型">
          <el-option
            v-for="item in optionsStore.getDictOptions('vehicle_type')"
            :key="item.id"
            :label="item.codeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="是否隐藏" prop="isHidden">
        <el-input v-model="paramsProps.row.isHidden" placeholder="请填写是否隐藏" clearable></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="部门id" prop="departmentId">
        <el-input-number v-model="paramsProps.row.departmentId" :precision="0" :min="1" :max="999999" />
      </el-form-item> -->
      <!-- <el-form-item label="上级公司" prop="pid"> -->
      <el-form-item label="选择公司车队" prop="departmentId">
        <el-tree-select
          v-model="paramsProps.row.departmentId"
          :data="parentMenus"
          check-strictly
          placeholder="请选择"
          :render-after-expand="false"
          clearable
          :default-expand-all="true"
          :props="treeProps"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消</el-button>
      <el-button type="primary" @click="handleSubmit"> 确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue';
import { type ElForm, ElMessage } from 'element-plus';
import { useOptionsStore } from '@/stores/modules/options';
import { useUserStore } from '@/stores/modules/user'; // Import user store
import type { SysDeptTree } from '@/api/types/system/dept';
import { getMenuTree, getMenuTree2 } from '@/api/modules/system/dept';
import type { VehicleScheduleRow } from '@/api/types/vehicleschedule/vehicleSchedule';
import { getVehicleScheduleListNopApi } from '@/api/modules/vehicleschedule/vehicleSchedule';

defineOptions({
  name: 'VehicleInfoForm'
});

const userStore = useUserStore(); // Initialize user store

// Computed property to check if current user is of type "user"
const isUserTypeUser = computed(() => {
  return userStore.userType === 'user';
});

const scheduleList = ref<VehicleScheduleRow[]>([]);
const scheduleProps = {
  label: 'title',
  value: 'id'
};

const optionsStore = useOptionsStore();
// 定义验证规则的接口，支持动态添加司机字段
  interface ValidationRules {
    vehicleNumber: { required: boolean; message: string }[];
    title: { required: boolean; message: string }[];
    sort: { required: boolean; message: string }[];
    vehicleTypeCd: { required: boolean; message: string }[];
    delFlag: { required: boolean; message: string }[];
    driverName?: { required: boolean; message: string }[];
    driverPhone1?: { required: boolean; message: string }[];
    driverName2?: { required: boolean; message: string }[];
    driverPhone2?: { required: boolean; message: string }[];
    driverName3?: { required: boolean; message: string }[];
    driverPhone3?: { required: boolean; message: string }[];
    [key: string]: any;
  }
  
  // 基础验证规则，不包含司机字段的验证
  const rules = reactive<ValidationRules>({
    vehicleNumber: [{ required: true, message: '请填写车辆编号' }],
    title: [{ required: true, message: '请填写名称' }],
    sort: [{ required: true, message: '请填写排序' }],
    vehicleTypeCd: [{ required: true, message: '请填写车辆类型 （字典表vehicle_type）' }],
    delFlag: [{ required: true, message: '请填写是否删除' }]
  });

// 新增响应式数据存储选中的排班类型
const selectedScheduleType = ref<string>('');

//
const parentMenus = ref<SysDeptTree[]>([]);
const treeProps = {
  label: 'name',
  value: 'id'
};

//

const visible = ref(false);
const paramsProps = ref<View.DefaultParams>({
  title: '',
  row: {},
  api: undefined,
  getTableList: undefined
});

// 根据排班类型获取司机数量
const getDriverCountByScheduleType = (scheduleType: string) => {
  switch (scheduleType) {
    case '2001001': // 全班制
      return 1;
    case '2001002': // 二班制
      return 2;
    case '2001003': // 三班制
      return 3;
    default:
      return 1;
  }
};

// 处理排班选择变化
const handleScheduleChange = (scheduleId: number) => {
  // 查找选中的排班类型
  const selectedSchedule = scheduleList.value.find(item => item.id === scheduleId);
  if (selectedSchedule && selectedSchedule.scheduleType) {
    selectedScheduleType.value = selectedSchedule.scheduleType;
    
    // 清除之前的司机姓名数据和手机号数据（保留第一个司机的driverName和driverPhone1）
    const driverCount = getDriverCountByScheduleType(selectedScheduleType.value);
    for (let i = 2; i <= 3; i++) {
      if (i > driverCount) {
        delete paramsProps.value.row[`driverName${i}`];
        delete paramsProps.value.row[`driverPhone${i}`];
      }
    }
    
    // 初始化编辑模式下的司机数据
    initializeDriverData();
  } else {
    selectedScheduleType.value = '';
  }
};

// 初始化编辑模式下的司机数据
const initializeDriverData = () => {
  // 当没有选择排班类型时也需要初始化默认的司机字段
  const driverCount = selectedScheduleType.value ? getDriverCountByScheduleType(selectedScheduleType.value) : 1;
  
  // 确保所有需要的司机字段都存在
  for (let i = 1; i <= driverCount; i++) {
    // 初始化司机姓名字段
    if (i === 1) {
      // 第一个司机使用 driverName
      if (!paramsProps.value.row.driverName) {
        paramsProps.value.row.driverName = '';
      }
    } else {
      // 其他司机使用 driverName2, driverName3
      if (!paramsProps.value.row[`driverName${i}`]) {
        paramsProps.value.row[`driverName${i}`] = '';
      }
    }
    
    // 初始化司机手机号字段
    if (!paramsProps.value.row[`driverPhone${i}`]) {
      paramsProps.value.row[`driverPhone${i}`] = '';
    }
  }
};

// 接收父组件传过来的参数
const acceptParams = (params: View.DefaultParams) => {
  paramsProps.value = params;
  visible.value = true;
  loadParentMenus();
};
const loadParentMenus = () => {
  // Use getMenuTree2 if user type is 'user', otherwise use getMenuTree
  const menuTreeApi = isUserTypeUser.value ? getMenuTree2 : getMenuTree;
  
  menuTreeApi({ excludeNodeId: paramsProps.value.row?.id }).then(res => {
    parentMenus.value = res.data;
  });
  getVehicleScheduleListNopApi({}).then(res => {
    // 确保res.data是数组
    scheduleList.value = Array.isArray(res.data) ? res.data : [res.data];
    
    // 如果已有选中的排班ID，初始化选中的排班类型
    if (paramsProps.value.row?.scheduleId) {
      // 延迟初始化，确保数据已加载
      setTimeout(() => {
        handleScheduleChange(paramsProps.value.row.scheduleId);
      }, 100);
    }
  });
};

// 重置验证规则为默认状态
const resetValidationRules = () => {
  // 重置所有司机相关的验证规则
  delete rules.driverName;
  delete rules.driverPhone1;
  delete rules.driverName2;
  delete rules.driverPhone2;
  delete rules.driverName3;
  delete rules.driverPhone3;
  
  // 重置选中的排班类型
  selectedScheduleType.value = '';
};

// 监听对话框显示状态变化，在关闭时重置验证规则
watch(visible, (newValue) => {
  if (!newValue) {
    // 对话框关闭时重置验证规则
    resetValidationRules();
    // 重置表单验证状态
    if (ruleFormRef.value) {
      ruleFormRef.value.resetFields();
    }
  }
});

// 在提交表单时动态设置司机字段的验证规则
const setupDriverValidationRules = () => {
  // 先清除所有司机相关的验证规则
  delete rules.driverName;
  delete rules.driverPhone1;
  delete rules.driverName2;
  delete rules.driverPhone2;
  delete rules.driverName3;
  delete rules.driverPhone3;
  
  // 根据排班类型设置司机字段的必填验证
  let driverCount = 1;
  if (selectedScheduleType.value) {
    driverCount = getDriverCountByScheduleType(selectedScheduleType.value);
  }
  
  // 设置必填验证规则
  if (driverCount >= 1) {
    rules.driverName = [{ required: true, message: '请填写司机姓名' }];
    rules.driverPhone1 = [{ required: true, message: '请填写司机手机号' }];
  }
  if (driverCount >= 2) {
    rules.driverName2 = [{ required: true, message: '请填写司机2姓名' }];
    rules.driverPhone2 = [{ required: true, message: '请填写司机手机号2' }];
  }
  if (driverCount >= 3) {
    rules.driverName3 = [{ required: true, message: '请填写司机3姓名' }];
    rules.driverPhone3 = [{ required: true, message: '请填写司机手机号3' }];
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<InstanceType<typeof ElForm>>();
const handleSubmit = async () => {
  try {
    // 提交表单前设置司机字段的验证规则
    setupDriverValidationRules();
    
    // 验证表单
    const isValid = await ruleFormRef.value!.validate();
    
    if (!isValid) return;
    
    await paramsProps.value.api!(paramsProps.value.row);
    ElMessage.success({ message: `${paramsProps.value.title}成功！` });
    paramsProps.value.getTableList!();
    
    // 提交成功后重置验证规则
    resetValidationRules();
    visible.value = false;
  } catch (error) {
    console.log(error);
    // 验证失败时不重置规则，保留以便用户查看错误提示
  }
};

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss"></style>
